package net.wofly.right.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.wofly.common.persistence.PageWrapper;
import net.wofly.common.util.ResultCode;
import net.wofly.common.util.ReturnBean;
import net.wofly.common.web.BaseController;
import net.wofly.right.domain.Role;
import net.wofly.right.domain.User;
import net.wofly.right.domain.UserReceivingAddr;
import net.wofly.right.service.IOrganizationService;
import net.wofly.right.service.IRoleService;
import net.wofly.right.service.IUserService;
import net.wofly.right.validator.UserValidator;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping(value = "/api/user")
@Api(description = "用户接口")
public class UserController extends BaseController {
    
    private static final String DEFAULT_PAGE_NUM = "1";
    private static final String DEFAULT_PAGE_SIZE = "10";
    
    @Resource
    IUserService iUserService;
    
    @Resource
    IRoleService iRoleService;
    
    @Resource
    IOrganizationService iOrganizationService;

	/*@RequestMapping(value = "/save", method = { RequestMethod.POST, RequestMethod.GET })
    @ResponseBody
	public User save(@RequestBody User entity) {
		return iUserService.save(entity);
	}

	@RequestMapping(value = "/delete", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void delete(String key) {
		iUserService.delete(key);
	}

	@RequestMapping(value = "/findOne", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public User findOne(String key) {
		return iUserService.findOne(key);
	}*/
    
    /**
     * 完全注册
     * <ul>
     * <li>此时才会真正写客户表（User）。</li>
     * <li>注册完成后，用户需要完善用户信息。</li>
     * <li>对于公众来说只需要完善，其完善的是：姓名，性别、出生年月、Email</li>
     * <li>对于单位客户来说，其要完善单位名称、单位地址、联系人姓、性别、出生年月、email、公司两张照片等信息。注册手机为联系人手机</li>
     * </ul>
     *
     * @param mobile
     * @param password
     * @param verifyCode
     */
    @ApiOperation(value = "完成注册")
    @ApiImplicitParams({@ApiImplicitParam(name = "mobile", value = "手机号码", required = true, dataType = "String",
            paramType = "form"), @ApiImplicitParam(name = "password", value = "密码（加密传输）", required = true, dataType =
            "String", paramType = "form"), @ApiImplicitParam(name = "verifyCode", value = "验证码", required = true,
            dataType = "String", paramType = "form")})
    @RequestMapping(value = "/finishRegisterByMobile", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> finishRegisterByMobile(String mobile, String password, String verifyCode) {
        ReturnBean<String> returnBean;
        String errorMessage = UserValidator.validateFinishRegisterByMobileParams(mobile, password, verifyCode);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<String>(-1, errorMessage);
        } else {
            returnBean = iUserService.finishRegisterByMobile(mobile, password, verifyCode);
        }
        return returnBean;
    }
    
    /**
     * 添加一个客户
     * <ul>
     * <li>业务员或团购专员及店员、会计都可以添加一个客户</li>
     * <li>添加客户时，要判断当前添加客户是否存在</li>
     * <li>业务员添加的客户需要会计审核</li>
     * <li>判断当前用户是否有审核添加客户的权限，如果有则直接添加成功</li>
     * </ul>
     *
     * @param user
     */
    @ApiOperation(value = "添加一个客户")
    @ApiImplicitParams({@ApiImplicitParam(name = "customer", value = "客户实体", required = true, dataType = "User")})
    @RequestMapping(value = "/addUser", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> addUser(@RequestBody User user) {
        ReturnBean<String> returnBean;
        String errorMessage = UserValidator.validateAddUserParams(user);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<String>(-1, errorMessage);
        } else {
            returnBean = iUserService.addUser(user);
        }
        return returnBean;
    }
    
    /**
     * 审核客户
     * <ul>
     * <li>通过添加进来的客户，需要有审核权限的用户审核才能使用</li>
     * <li>需要将审核记录写入客户注册审核表中</li>
     * </ul>
     *
     * @param customer
     */
    @ApiOperation(value = "审核客户")
    @ApiImplicitParams({@ApiImplicitParam(name = "customer", value = "客户实体", required = true, dataType = "User"),
            @ApiImplicitParam(name = "userID", value = "审核人ID", required = true, dataType = "String", paramType =
                    "form")})
    @RequestMapping(value = "/checkUser", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> checkUser(@RequestBody User customer, String userID) {
        ReturnBean<String> returnBean;
        String errorMessage = UserValidator.validateCheckUserParams(customer, userID);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<String>(-1, errorMessage);
        } else {
            returnBean = iUserService.checkUser(customer, userID);
        }
        return returnBean;
    }
    
    
    /**
     * 登陆
     * <ul>
     * <li>目前只有手机，可以支持根据帐号来判断登陆帐号类型</li>
     * <li>前后交互时，密码加密处理</li>
     * </ul>
     *
     * @param accountID
     * @param password
     */
    @ApiOperation(value = "登录接口")
    @ApiImplicitParams({@ApiImplicitParam(name = "accountID", value = "手机号码或者邮箱", required = true, dataType = "String", paramType = "form"),
            				@ApiImplicitParam(name = "password", value = "密码（加密传输）", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<User> login(HttpServletRequest request, String accountID, String password) {
        
        ReturnBean<User> returnBean;
        
        String errorMessage = UserValidator.validateLoginParams(accountID, password);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<User>(-1, errorMessage);
        } else {
            returnBean = iUserService.login(request, accountID, password);
        }
        return returnBean;
    }

    /**
     * 登录接口for移动端
     * <ul>
     * <li>目前只有手机，可以支持根据帐号来判断登陆帐号类型</li>
     * <li>前后交互时，密码加密处理</li>
     * </ul>
     *
     * @param accountID
     * @param password
     */
    @ApiOperation(value = "登录接口for移动端")
    @ApiImplicitParams({@ApiImplicitParam(name = "accountID", value = "手机号码或者邮箱", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "password", value = "密码（加密传输）", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/loginForMobile", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<User> loginForMobile(HttpServletRequest request, String accountID, String password) {

        ReturnBean<User> returnBean;

        String errorMessage = UserValidator.validateLoginParams(accountID, password);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            returnBean = iUserService.loginForMobile(request, accountID, password);
        }
        return returnBean;
    }
    
    /**
     * 登出
     *
     * @param userID
     */
    @ApiOperation(value = "退出接口")
    @ApiImplicitParam(name = "userID", value = "客户ID", required = true, dataType = "String", paramType = "form")
    @RequestMapping(value = "/logout", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> logout(String userID) {
        Subject subject = SecurityUtils.getSubject();
        subject.getSession().removeAttribute(userID);
        return new ReturnBean<String>(ResultCode.SUCCESS, "退出成功");
    }
    
    /**
     * 发送手机验证码
     * <ul>
     * <li></li>
     * </ul>
     *
     * @param mobile
     */
    @ApiOperation(value = "发送注册用户手机验证码")
    @ApiImplicitParam(name = "mobile", value = "手机号码", required = true, dataType = "String", paramType = "form")
    @RequestMapping(value = "/sendMobileVerifyCodeForReg", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> sendMobileVerifyCodeForReg(String mobile) {
        ReturnBean<String> returnBean;
        String errorMessage = UserValidator.validateSendMobileVerifyCode(mobile);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<String>(-1, errorMessage);
        } else {
            returnBean = iUserService.sendMobileVerifyCodeForReg(mobile);
        }
        return returnBean;
    }
    
    /**
     * 发送手机验证码
     * <ul>
     * <li></li>
     * </ul>
     *
     * @param mobile
     */
    @ApiOperation(value = "发送注册用户手机验证码")
    @ApiImplicitParam(name = "mobile", value = "手机号码", required = true, dataType = "String", paramType = "form")
    @RequestMapping(value = "/sendMobileVerifyCode", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> sendMobileVerifyCode(String mobile) {
        ReturnBean<String> returnBean;
        String errorMessage = UserValidator.validateSendMobileVerifyCode(mobile);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<String>(-1, errorMessage);
        } else {
            returnBean = iUserService.sendMobileVerifyCode(mobile);
        }
        return returnBean;
    }
    
    
    /**
     * 删除员工维护客户
     *
     * @param customerFollowID
     */
    public ReturnBean<String> delUserFollow(String customerFollowID) {
        return null;
    }
    
    /**
     * 获取所有客户
     *
     * @param status
     * @param pageNum
     * @param pageSize
     */
    @ApiOperation(value = "获取所有客户")
    @ApiImplicitParams({@ApiImplicitParam(name = "status", value = "客户状态(默认有效客户)", required = true, dataType = "int",
            paramType = "form"),
            @ApiImplicitParam(name = "pageNum", value = "页码（默认第一页）", required = true, dataType = "int", paramType =
                    "form"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数（默认10条）", required = true, dataType = "int",
                    paramType = "form")})
    @RequestMapping(value = "/getAllUser", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<PageWrapper<User>> getAllUser(
            @RequestParam(defaultValue = "1") Integer status,
            @RequestParam(defaultValue = DEFAULT_PAGE_NUM) Integer pageNum,
            @RequestParam(defaultValue = DEFAULT_PAGE_SIZE) Integer pageSize) {
        return iUserService.getAllUser(status, pageNum, pageSize);
    }
    
    /**
     * 获取提定员工的维护客户
     *
     * @param salesUserID
     */
    @ApiOperation(value = "获取我的客户")
    @ApiImplicitParams({@ApiImplicitParam(name = "salesUserID", value = "员工ID", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/getMyCustomFollow", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<List<User>> getMyCustomFollow(String salesUserID) {
        ReturnBean<List<User>> returnBean;
        String errorMessage = UserValidator.validateUserID(salesUserID);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<List<User>>(-1, errorMessage);
        } else {
            returnBean = iUserService.getMyUserFollow(salesUserID);
        }
        return returnBean;
    }
    
    /**
     * 获取客户类型
     *
     *
     */
    @ApiOperation(value = "获取客户类型")
    @RequestMapping(value = "/getCustomType", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<List<Role>> getCustomType() {
    		return iRoleService.getCustomType() ;
    }
    
    /**
     * 获取所有销售
     * 
     *
     */
    @ApiOperation(value = "获取公司业务员(包括业务员和团购专员)")
    @RequestMapping(value = "/getAllSale", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<List<User>> getAllSale() {
    		return iUserService.getAllSales() ;
    }
    
    @RequiresPermissions(value = {"/api/right/addPersonalCustom"})
    @ApiOperation(value = "添加个人客户", notes = "添加个人客户")
    @ApiImplicitParams({@ApiImplicitParam(name = "user", value = "个人客户信息", required = true, dataType = "User", paramType = "body")})
    @RequestMapping(value = "/addPersonalCustom", method = {RequestMethod.POST})
    @ResponseBody
    	public ReturnBean<String> addPersonalCustom(@RequestBody User user){
    		ReturnBean<String> returnBean;
        String errorMessage = UserValidator.validateAddPersonalCustomParams(user) ;
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<String>(-1, errorMessage);
        } else {
            returnBean = iUserService.addPersonalCustom(user) ;
        }
        return returnBean;
    }
       

    @ApiOperation(value = "设置员工的维护客户")
    @ApiImplicitParams({@ApiImplicitParam(name = "employeeUserID", value = "员工ID", required = true, dataType ="String", paramType = "form"),
            @ApiImplicitParam(name = "customerUserID", value = "客戶ID", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/setUserFollow", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> setUserFollow(String employeeUserID, String customerUserID) {
        ReturnBean<String> returnBean;
        String errorMessage = UserValidator.validateSetUserFollowParams(employeeUserID, customerUserID);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<String>(-1, errorMessage);
        } else {
            returnBean = iUserService.setUserFollow(employeeUserID, customerUserID);
        }
        return returnBean;
    }
    
    @ApiOperation(value = "校验用户是否合登陆")
    @ApiImplicitParams({@ApiImplicitParam(name = "userID", value = "员工ID", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/checkUserLoginStatus", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> checkUserLoginStatus(HttpServletRequest request, String userID) {
        Subject subject = SecurityUtils.getSubject();
        Object o = subject.getSession().getAttribute(userID);
        if (null==o) {
        		return new ReturnBean<String>(99, "当前用户己退出登陆");
        }
        return new ReturnBean<String>(ResultCode.SUCCESS, "当前用户登陆中");
    }
    
    
    @ApiOperation(value = "确认订单中，获取客户列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "userID", value = "员工ID", required = true, dataType ="String", paramType = "form"),
        					@ApiImplicitParam(name = "orderType", value = "订单类型", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/getUserForOrder", method = {RequestMethod.POST} )
    @ResponseBody
    public ReturnBean<List<UserReceivingAddr>> getUserForOrder(HttpServletRequest request, String userID ,String orderType) {
    		ReturnBean<List<UserReceivingAddr>> returnBean;
        String errorMessage = UserValidator.validateGetUserForOrder(userID, orderType);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            returnBean = iUserService.getUserForOrder(orderType, userID) ;
        }
        return returnBean;
    		
    		
    }
    
    @ApiOperation(value = "确认订单中")
    @ApiImplicitParams({@ApiImplicitParam(name = "userID", value = "员工ID", required = true, dataType ="String", paramType = "form"),
        					@ApiImplicitParam(name = "orderType", value = "订单类型", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/saveUser", method = {RequestMethod.POST} )
    @ResponseBody
    public ReturnBean<List<UserReceivingAddr>> saveUser(HttpServletRequest request, String userID ,String orderType) {
    		ReturnBean<List<UserReceivingAddr>> returnBean;
        String errorMessage = UserValidator.validateGetUserForOrder(userID, orderType);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            returnBean = iUserService.getUserForOrder(orderType, userID) ;
        }
        return returnBean;
    }
    
    /**
     * 查询所有流通的和酒店的客户，在客户列表中搜索条件获取客户信息用
     *
     * @return
     */
    //客户列表不需要，因为本身就是查询的客户信息
 /*   @ApiOperation(value = "查询所有流通的和酒店的客户，在客户列表中搜索条件获取客户信息用")
    @RequestMapping(value = "/saveUser", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<List<User>> getCustomerForCustomerSearch() {
        return iUserService.getCustomerForCustomerSearch();
    }*/
    
}
